package com.fivestyle.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fivestyle.common.result.R;
import com.fivestyle.common.tool.OrderNoUtil;
import com.fivestyle.entity.Book;
import com.fivestyle.entity.Orders;
import com.fivestyle.entity.User;
import com.fivestyle.mapper.OrderMapper;
import com.fivestyle.service.BookService;
import com.fivestyle.service.OrderService;
import com.fivestyle.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import java.util.HashMap;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 张代钊
 * @since 2021-08-04
 */
@Service
public class OrderServiceImpl extends ServiceImpl<OrderMapper, Orders> implements OrderService {

    @Autowired
    private UserService userService;

    @Autowired
    private BookService bookService;

    @Override
    public R getOrderList(Long current, Long size, String userId) {
        Page<Orders> page = new Page<>(current, size);
        QueryWrapper<Orders> wrapper = new QueryWrapper<>();

        wrapper.eq("user_id",userId).eq("status",0).orderByDesc("updated");
        Page<Orders> page1 = baseMapper.selectPage(page, wrapper);

        long total = page1.getTotal();
        List<Orders> records = page1.getRecords();

        return R.ok().data("total",total).data("records",records);
    }

    @Override
    public R getAllOrder(String userId) {
//        baseMapper.getAllOrder(userId);
        QueryWrapper<Orders> wrapper = new QueryWrapper<>();
        wrapper.eq("user_id", userId).groupBy("order_no").select("order_no");
        List<Orders> orders = baseMapper.selectList(wrapper);

        HashMap<String , List<Orders>> map = new HashMap<>();

        for (Orders order : orders) {
            wrapper.clear();
            List<Orders> list = baseMapper.selectList(wrapper.eq("order_no",order.getOrderNo()));
            map.put(order.getOrderNo(),list);
        }

        return R.ok().data("allOrdersList",map).message("成功获取该用户的全部订单信息！");
    }

    @Transactional
    @Override
    public R updateAddr(String json) {
        JSONObject jsonObject = JSONObject.parseObject(json);
        String userId = jsonObject.get("userId").toString();
        String addr = jsonObject.get("addr").toString();

        List<Orders> list = baseMapper.selectList(new QueryWrapper<Orders>().eq("user_id", userId).eq("status",0));
        try {
            for (Orders orders : list) {
                orders.setUserAddr(addr);
                baseMapper.updateById(orders);
            }
            return R.ok().message("用户收货地址已成功更新！");
        }catch (Exception e){
            e.printStackTrace();
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return R.error().message("用户收货地址更新报错！");
        }
    }

    @Transactional
    @Override
    public R addSomeToBuy(String bookId, String userId) {

        if (bookId.isEmpty() || userId.isEmpty()){
            return R.error().message("创建订单失败,bookId 或者 userId为空！");
        }

        QueryWrapper<Orders> wrapper = new QueryWrapper<>();
        wrapper.eq("book_id",bookId).eq("user_id", userId).eq("status",0);
        Orders order1 = baseMapper.selectOne(wrapper);
//        如果之前有过订单,但是还未支付
        if(order1!=null){
            return this.getOrderList(Long.parseLong("1"),Long.parseLong("5"),userId).message("购物车中已有该书籍，请勿反复添加！");
        }else {
            User userInfo = userService.getById(userId);
            Book bookInfo = bookService.getById(bookId);

            //创建Order对象，向order对象里面设置需要数据
            Orders order = new Orders();


//            设置订单号，在同一个购物车里面，设置为同一个订单号
            wrapper.clear();
            wrapper.eq("user_id",userId).eq("status",0).orderByAsc("created");
            Orders orders = baseMapper.selectOne(wrapper);
            if (orders!=null){
                order.setOrderNo(orders.getOrderNo());
            }else {
                order.setOrderNo(OrderNoUtil.getOrderNo());
            }

            order.setBookId(bookInfo.getId()); //课程id
            order.setBookCount(1);
            order.setBookPrice(bookInfo.getPrice());
            order.setBookImg(bookInfo.getImg());
            order.setBookName(bookInfo.getBookName());
            order.setMoneyTotal(bookInfo.getPrice());

            order.setStatus(0);

            order.setUserAddr(userInfo.getAddr());
            order.setUserId(userInfo.getId());
            order.setUserName(userInfo.getName());
            order.setUserPhone(userInfo.getPhone());
            try {
                baseMapper.insert(order);
            }catch (Exception e){
                e.printStackTrace();
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                return R.error().message("插入订单失败！");
            }

            return this.getOrderList(Long.parseLong("1"),Long.parseLong("5"),userId).message("成功添加到购物车");
        }
    }


}
